package com.zhike.common.utils;

import java.io.File;
import java.io.IOException;
import java.awt.*;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import java.awt.geom.RoundRectangle2D;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.Random;

public class PicUtil {

  private String value;

  public BufferedImage Paint(String name, int width, int height, String fontFilePath, int fontSize) throws Exception {
    if (name == null || name.equals("")) {
      throw new Exception("名称不能为空");
    }
    int nameLen = name.length();
    String nameWritten;
    // 如果用户输入的姓名少于等于2个字符，不用截取
    if (nameLen <= 2) {
      nameWritten = name;
    } else {
      // 如果用户输入的姓名大于等于3个字符，截取后面两位
      String first = name.substring(0, 1);
      if (isChinese(first)) {
        // 截取倒数两位汉字
        nameWritten = name.substring(nameLen - 2);
      } else {
        // 截取后面的两个英文字母
        // nameWritten = name.substring(nameLen - 2).toUpperCase();
        nameWritten = first.toUpperCase();
      }
    }

    this.value = nameWritten;

    BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

    Graphics2D g2 = (Graphics2D) bi.getGraphics();
    g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
        RenderingHints.VALUE_TEXT_ANTIALIAS_ON);

    this.paintLinearColor(g2, width, height);
    // g2.setBackground(this.getRandomColor());

    // g2.clearRect(0, 0, width, height);
    g2.setPaint(Color.WHITE);
    // g2.setTransform();
    File fontFile = new File(fontFilePath + "simhei.ttf");
    Font font = Font.createFont(Font.TRUETYPE_FONT, fontFile);
    GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
    ge.registerFont(font);

    font = new Font("SimHei", Font.PLAIN, fontSize);
    g2.setFont(font);

    // 两个字及以上
    if (this.value.length() >= 2) {
      // String firstWritten = nameWritten.substring(nameWritten.length() -1,
      // this.value.length());
      FontMetrics fm = g2.getFontMetrics(font);
      int textWidth = fm.stringWidth(this.value);
      int widthX = (width - textWidth) / 2;
      if (!isChinese(this.value)) {
        String firstWrittenUpper = this.value.toUpperCase();
        g2.drawString(firstWrittenUpper, widthX, 70);
      } else {
        g2.drawString(this.value, widthX, 70);
      }
    }
    // 一个字
    if (this.value.length() == 1) {
      // 中文
      if (isChinese(this.value)) {
        g2.drawString(this.value, 25, 70);
      }
      // 英文
      else {
        FontMetrics fm = g2.getFontMetrics(font);
        int textWidth = fm.stringWidth(this.value);
        int widthX = (width - textWidth) / 2;
        g2.drawString(this.value.toUpperCase(), widthX, 70);
      }
    }
    // System.out.printf("name is %s \n",this.value);

    return bi;
  }

  public void write(BufferedImage bufferedImage, File target) {
    try {
      ImageIO.write(bufferedImage, "png", target);
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

  /**
   * 判断字符串是否为中文
   * 
   * @param str
   * @return
   */
  public static boolean isChinese(String str) {
    String regEx = "[\\u4e00-\\u9fa5]+";
    Pattern p = Pattern.compile(regEx);
    Matcher m = p.matcher(str);
    if (m.find())
      return true;
    else
      return false;
  }

  /**
   * 获得随机颜色
   * 
   * @return
   */
  public Color getRandomColor() {
    String[] beautifulColors = new String[] { "141,224,157", "116,219,216", "120,195,255", "167,157,255", "255,161,217",
        "252,136,136", "247,199,94" };
    int len = beautifulColors.length;
    Random random = new Random();
    String[] color = beautifulColors[random.nextInt(len)].split(",");
    return new Color(Integer.parseInt(color[0]), Integer.parseInt(color[1]),
        Integer.parseInt(color[2]));
  }

  /**
   * 设置线性渐变色
   * 
   * @param g2d
   * @param width
   * @param height
   */
  public void paintLinearColor(Graphics2D g2d, int width, int height) {
    // 渐变底色
    int startX = 0;
    int startY = 0;
    int endX = width;
    int endY = height;
    float[] fractions = { 0.0f, 0.5f }; // 颜色过渡点的位置数组
    Color startColor = new Color(153, 204, 255);
    Color endColor = new Color(0, 102, 255);
    Color[] colors = { startColor, endColor }; // 颜色过渡点的颜色数组
    // 垂直线性渐变（0,0,起始颜色,0,height,结束颜色）
    // 45°线性渐变(0,0,起始颜色,width,height,结束颜色)
    LinearGradientPaint gradientPaint = new LinearGradientPaint(startX, startY, 0, endY, fractions, colors);
    // GradientPaint gradientPaint = new GradientPaint(startX, startY, startColor,
    // endX, endY, endColor);
    g2d.setPaint(gradientPaint);
    g2d.fillRect(startX, startY, endX, endY);
  }

  /**
   * 图片做圆角处理
   * 
   * @param image
   * @param cornerRadius
   * @return
   */
  public BufferedImage makeRoundedCorner(BufferedImage image, int cornerRadius) {
    int w = image.getWidth();
    int h = image.getHeight();
    BufferedImage output = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
    Graphics2D g2 = output.createGraphics();
    g2.setComposite(AlphaComposite.Src);
    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    g2.setColor(Color.WHITE);
    g2.fill(new RoundRectangle2D.Float(0, 0, w, h, cornerRadius, cornerRadius));
    g2.setComposite(AlphaComposite.SrcAtop);
    g2.drawImage(image, 0, 0, null);
    g2.dispose();
    return output;
  }

  public String Create(String path, String subName, BufferedImage image) {
    BufferedImage rounded = this.makeRoundedCorner(image, 50);
    String fullPath = path + subName + ".png";
    File f = new File(fullPath);
    if (!f.exists()) {
      f.mkdirs();
    }
    write(rounded, f);
    return f.getName();
  }

  public File Create(String nameKey, BufferedImage image) {
    BufferedImage rounded = this.makeRoundedCorner(image, 50);
    File f = new File(nameKey + ".png");
    if (!f.exists()) {
      f.mkdirs();
    }
    write(rounded, f);
    return f;
  }

  public static void main(String[] args) throws Exception {
    String value = "智科";
    PicUtil pu = new PicUtil();
    String path = pu.Create("C:\\", "450545", pu.Paint(value, 100, 100, "", 45));
    System.out.println(path);
  }
}
